<template>
  <div class="article_list">
    <van-pull-refresh :success-duration="1500" :success-text="tipText" v-model="articleIsLoading" @refresh="onRefresh">

      <van-list :error.sync="error" error-text="请求失败，点击重新加载" v-model="loading" :finished="finished"
        finished-text="没有更多了" @load="onLoad">
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
     -->
        <!-- 文章item组件 -->
        <ArticleItem :article="item" v-for="item in list" :key="item.art_id+''"></ArticleItem>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleList } from '@/api/article'
import ArticleItem from '@/components/acrticle-item/index.vue'
export default {
  name: 'article-list',
  props: {
    // 频道id
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      params: {
        channel_id: this.channelId,
        timestamp: Date.now(),
        with_top: 0
      },

      error: false, // 控制列表失败状态
      articleIsLoading: false, // 下拉刷新控制状态
      tipText: ''
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data: res } = await getArticleList(this.params)
        // console.log(res)
        this.params.timestamp = res.data.pre_timestamp
        this.list.push(...res.data.results)
        // 加载状态结束
        this.loading = false
        if (res.data.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        // this.$toast('获取失败')
        // 开启错误信息
        this.error = true
        // 关闭加载状态
        this.loading = false
      }

      // 数据全部加载完成
    },
    async onRefresh () {
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 0
        })
        console.log(res)
        this.list.unshift(...res.data.results)
        this.articleIsLoading = false
        // 设置成功提示文本
        this.tipText = `加载成功，共加载${res.data.results.length}条`
      } catch (err) {
        this.tipText = '加载失败，请重试'
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArticleItem
  },
  created () {

  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.article_list {
  height: 80vh;
  overflow-y: scroll;
}
</style>
